package myProject.gwt.client.dynamicTable;

import java.util.HashSet;

import myProject.gwt.client.simpleTable.AbstractTable;
import myProject.gwt.client.simpleTable.IHeader;

import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

public class DynamicGrid extends ScrollPanel{

	private SimplePanel content = new SimplePanel();
	private Element contentElement;
	private HashSet<Integer> cache = new HashSet<Integer>();
	private static int colWidth = 101;
	
	public DynamicGrid(){
		this.add(content);
		this.setStylePrimaryName("scroll");
		content.setStylePrimaryName("container");
		contentElement = content.getElement();
		
		this.addScrollHandler(new ScrollHandler(){

			@Override
			public void onScroll(ScrollEvent event) {
				repaint();				
			}
			
		});
		
		drawRows(0, 30, 0, 20);
	}
	
	
	
	private void repaint(){
		int sc = this.getScrollPosition();
		int startRow = sc / 21;
		int endRow = startRow + (this.getOffsetHeight() / 21);
		
		int hsc = this.getHorizontalScrollPosition();
		int startCol = hsc / colWidth; 
		int endCol = startCol + (this.getOffsetWidth() / colWidth)+2;
		drawRows(startRow, endRow, startCol, endCol);
	}
	
	
	private void drawRows(int startRow, int endRow, int startCol, int endCol){
		StringBuilder sb = new StringBuilder();
		for(int row=startRow; row<endRow; row++){
			
			for(int col=startCol; col<endCol; col++){				
				int key = row*65536+col;
				if(cache.contains(key))continue;
				cache.add(key);

				int left = col*colWidth;
				int top = row*21;
				String className = "box";
				if((row % 2) == 0) className += " evenRow";
				else className += " oddRow";
				
				String text = row+"/"+col;
				
				sb.append("<div class=\""+className+"\" style=\"left: "+left+"px; top: "+top+"px;\">"+text+"</div>");
			}
		}
		//String text = contentElement.getInnerHTML() + sb.toString();
		//contentElement.setInnerHTML(sb.toString());
		HTML html = new HTML(sb.toString());
		contentElement.appendChild(html.getElement());
	}




	
}
